
import React, { useRef, useState, useEffect } from "react"
import { ConfigProvider, Empty, Table, Button, Space, Pagination } from "antd"
import styles from "./xx-table.module.scss"
import TableActionPanel from "./actionPanel";
import Notfound from "../notFound/not-found";
import XxPagination from "../xx-pagination/xx-pagination";
import dayjs from "dayjs";
import disparseColumns from "./disparseColumns";


/**
 * @author 韩
 * @param {*} param0 
 * @returns 
 * @desc API说明：size 为表格尺寸

 */

const XxTable = ({
  selectRecords = [],
  tablePanelConfig = [],
  showAllRows,
  dataSource = [],
  scroll = {},
  createClick = () => { },
  pagination,
  size = "small",
  loading = false,
  columns = [],
  rowSelection = Object,
  showActionPanel = true,
  showSearchPanel = true,
  ...props
}) => {

  // props
  const {
    onClick,
    onDoubleClick,
    rowKey = "id",
  } = props



  const [useColumns, setUseColumns] = useState([columns]);
  useEffect(() => {
    setUseColumns(columns)
  }, [columns])


  // const fiterColumns = props.columns.filter(item => !item.hideConfig)
  const { deductHeight = 0 } = props // 允许组件外部手动扣除一定高度
  // 获取widnow高宽
  const getWindowSize = () => ({
    innerHeight: window.innerHeight,
    innerWidth: window.innerWidth,
  })

  const [windowSize, setWindowSize] = useState(getWindowSize())

  const handleResize = () => {
    // console.log(getWindowSize())
    setWindowSize(getWindowSize())
  }
  // 监听窗口变化，重新获取windowSize
  useEffect(() => {
    window.addEventListener('resize', handleResize)
    //卸载组件的时候销毁resize监听事件
    return () => window.removeEventListener('resize', handleResize)
  }, [])
  const [scrollY, setScrollY] = useState()
  const [clientTop, setClientTop] = useState(0)
  // 根据页面高度动态设置表格垂直出现滚动的高度
  const tabCenterRef = useRef();
  const setScrollYFun = () => {

    if (tabCenterRef.current.getBoundingClientRect().top) {
      const winClientTop = tabCenterRef.current.getBoundingClientRect().top
      setClientTop(winClientTop)
      setScrollY((preScrollY) => {
        // console.log('showAllRows',showAllRows)
        if (showAllRows) {
          return 'max-content'
        }
        // 表格高度 = 页面高度 - 表格元素距离顶部距离 - 固定值 - 扣除高度
        // console.log(windowSize.innerHeight,winClientTop,)
        return windowSize.innerHeight - winClientTop - deductHeight
      })
    } else {
      setScrollY((preScrollY) => {
        if (showAllRows) {
          return 'max-content'
        }
        // 表格高度 = 页面高度 - 表格元素距离顶部距离 - 固定值 - 扣除高度
        return windowSize.innerHeight - clientTop - deductHeight
      })
    }
  }

  useEffect(() => {
    // 页面元素还没有创建完成，使用延迟加载
    if (tabCenterRef.current.getBoundingClientRect().top) {
      setScrollYFun()
    } else {
      setTimeout(() => {
        setScrollYFun()
      }, 30)
    }
  }, [windowSize])
  /**
   * 表格事件
   *  onClick：单击
   *  onDoubleClick：双击
   *  onContextMenu：右击
   *  onMouseEnter：鼠标移入行
   *  onMouseLeave：鼠标移出行
   */
  // const onRow = onRowEvent
  const onRow = (record, index) => {
    return {
      onClick: (e) => {
        if (onClick) {
          onClick(record, index)
        }
      },
      onDoubleClick: (e) => {
        if (onDoubleClick) {
          onDoubleClick(record, index)
        }
      },
      onContextMenu: (e) => { },
      onMouseEnter: (e) => { },
      onMouseLeave: (e) => { },
    }
  }

  const tabRef = useRef()
  useEffect(() => {
    if (scrollY) {
      const div = tabRef.current
      console.log("表格组件打印div：\n", div)
      if (div) {

        div.style.height = '100%'
        const scroHeight = dataSource.length > 0 ? 0 : 0

        const tableLoading = div.getElementsByClassName('ant-spin-nested-loading')[0]

        if (tableLoading) {
          tableLoading.style.height = '100%'
        }

        const tableSpinContainer = div.getElementsByClassName('ant-spin-container')[0]
        if (tableSpinContainer) {
          if (dataSource.length === 0) {
            tableSpinContainer.style.display = null
            tableSpinContainer.style.flexDirection = null
            tableSpinContainer.style.height = '100%'
          } else {
            tableSpinContainer.style.display = "flex"
            tableSpinContainer.style.flexDirection = "column"
          }
        }

        const emptyTable = div.getElementsByClassName('ant-table ant-table-empty')[0]
        if (emptyTable) {
          emptyTable.style.height = '100%'
        }

        const tableOuter = div.getElementsByClassName('ant-table ant-table-fixed-header')[0]
        if (tableOuter) {
          tableOuter.style.height = '100%'
        }

        const tableContainer = div.getElementsByClassName('ant-table-container')[0]
        if (tableContainer) {
          tableContainer.style.height = '100%'
        }

        const tableContent = div.getElementsByClassName('ant-table-content')[0]
        if (tableContent) {
          const table = tableContent.getElementsByTagName('table')[0]
          if (table) {
            if (dataSource?.length === 0) {
              table.style.height = '100%'
            } else {
              table.style.height = null
            }
          }
        }

        const tableBody = div.getElementsByClassName('ant-table-body')[0]
        if (tableBody) {

          const container = div.getElementsByClassName('ant-table-container')[0]
          const containerHeight = container.offsetHeight


          const header = div.getElementsByClassName('ant-table-header')[0]
          const headerHeight = header.offsetHeight

          const bodyHeight = containerHeight - headerHeight
          tableBody.style.maxHeight = `${bodyHeight - 1 - scroHeight}px`
          tableBody.style.height = `${bodyHeight - 1 - scroHeight}px`

          const table = tableBody.getElementsByTagName('table')[0]
          if (table) {
            if (dataSource?.length === 0) {
              table.style.height = '100%'
            } else {
              table.style.height = null
            }
          }
        }
      }

    }
  }, [tabRef])



  return (
    <>


      <ConfigProvider renderEmpty={Notfound}>
        {
          showActionPanel ? <TableActionPanel
            columns={columns} //原始配置
            useColumns={useColumns} //真正使用的
            setUseColumns={setUseColumns}
            selectRecords={selectRecords}
            tablePanelConfig={tablePanelConfig} /> : null
        }

        <div className={styles.container}>
          <div className="tab-center"
            ref={tabCenterRef}
          >
            <Table
              // className="reset-tab-class"
              ref={tabRef}
              loading={loading}
              scroll={{ ...scroll, y: scroll.y || scrollY }}
              style={{

              }}
              pagination={{ ...pagination }}
              columns={disparseColumns(columns)}
              dataSource={dataSource}
              size={windowSize.innerWidth < 1600 ? 'small' : 'default'}
              bordered={true}
              onRow={onRow}
              {...props}
              rowKey={rowKey}
              rowSelection={{
                ...rowSelection,
              }}
            />

          </div>
        </div>
        <div
          style={{
            display: "flex",
            justifyContent: "flex-end",
            padding: "10px 0"
          }}
        >
          {
            pagination && <XxPagination {...pagination} />
          }
        </div>
      </ConfigProvider >

    </>

  )
}
export default XxTable;